import { createRouter, createWebHistory } from "vue-router";
const modules = import.meta.glob("../views/**/**.vue");

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "login",
      /*@ts-ignore */
      component: () => import("../views/LoginView.vue"),
    },
  ],
});

const LOGIN_USER = localStorage.getItem("LOGIN_USER");
const routes = [];
if (LOGIN_USER) {
  const menuList = JSON.parse(LOGIN_USER).submenuRespList || [];
  for (let i = 0; i < menuList.length; i++) {
    const element = menuList[i];
    if (element.menuEntityList != null) {
      for (let j = 0; j < element.menuEntityList.length; j++) {
        const item = element.menuEntityList[j];
        routes.push(item);
      }
    } else {
      routes.push(element);
    }
  }
}

const children: any = [];
routes.map((item: any) => {
  const route = {
    path: item.route,
    name: item.id,
    component: modules[`../views/pages/${item.component}View.vue`],
  };
  children.push(route);
});

router.addRoute({
  path: "/layout",
  name: "layout",
  redirect: "/home",
  component: () => import("../views/LayoutView.vue"),
  children: children,
});

router.beforeEach((to, from, next) => {
  if (to.name === "login") {
    next();
  } else {
    if (localStorage.getItem("LOGIN_USER")) {
      next();
    } else {
      next({ name: "login" });
    }
  }
});

export default router;
